import random
from douyin.models import accounts
from utils.error_code import ErrorCode
from douyin.common import common_request
from utils.reply import reply
from lib.logger import logger


def request_search(keyword: str, cookie: str, offset: int = 0, limit: int = 10, common_params: str = '') -> tuple[dict, bool]:
    """
    请求抖音获取搜索信息
    """
    logger.info(f"开始执行request_search方法，keyword: {keyword}, cookie: {cookie}, offset: {offset}, limit: {limit}, common_params: {common_params}")

    params = {
        "keyword": keyword,
        "search_channel": 'aweme_general',
        "search_source": 'search_history',
        "query_correct_type": '1',
        "is_filter_search": '0',
        'offset': offset,
        'count': limit
    }
    headers = {"cookie": cookie}
    resp, succ = common_request('/aweme/v1/web/general/search/single/', params, headers, common_params)
    if not succ:
        return resp, succ

    logger.info(f"结束执行request_search方法，keyword: {keyword}, offset: {offset}, limit: {limit}, resp: {resp}, succ: {succ}")

    return resp, succ


def douyin_search(keyword: str, offset: int = 0, limit: int = 10, common_params=None):
    """
    获取视频搜索
    """
    logger.info(f"开始执行douyin_search方法，keyword: {keyword}, offset: {offset}, limit: {limit}, common_params: {common_params}")

    _accounts = accounts.load(type='douyin')
    random.shuffle(_accounts)
    for account in _accounts:
        if account.get('expired', 0) == '1':
        # 这里可能需要注意数据类型，前面定义的expired应该是整数类型，这里比较用的是字符串'1'，可能需要根据实际情况调整
            continue
        account_id = account.get('id', '')
        res, succ = request_search(keyword, account.get('cookie', ''), offset, limit, common_params)
        if res == {} or not succ:
            accounts.expire(account_id)
            logger.error(
                f'搜索失败，账号: {account_id}, 关键词: {keyword}, 偏移量: {offset}, 限制数量: {limit}, 结果: {res}')
            continue
        logger.info(
            f'搜索成功，账号: {account_id}, 关键词: {keyword}, 偏移量: {offset}, 限制数量: {limit}, 结果: {res}')
        return reply(ErrorCode.OK, '成功', res)

    logger.warning(f'搜索失败，关键词: {keyword}, 偏移量: {offset}, 限制数量: {limit}')
    return reply(ErrorCode.NO_ACCOUNT, '请先添加账号')